import requests
from bs4 import BeautifulSoup


class StockDetail:
    def __init__(self, code, name, price):
        self.code = code       # 股票代码
        self.name = name       # 股票名称
        self.price = price     # 当前价格

    def __repr__(self):
        return f"Stock(code='{self.code}', name='{self.name}', price={self.price})"


def get_stock_info(stock_code):

    stock_code = convert_stock_code(stock_code)
    url = f"https://finance.sina.com.cn/realstock/company/{stock_code}/nc.shtml"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"
    }

    response = requests.get(url, headers=headers)
    response.encoding = 'GBK'  # 设置编码格式

    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')

        # 获取股票名称
        stock_name = ''
        stock_name_tag = soup.find('h1', id='stockName')
        if stock_name_tag:
            stock_name = stock_name_tag.find(
                'i', class_='c8_name').text.strip()  # 股票名称
            stock_code = stock_name_tag.find('span').text.strip()  # 股票代码

        # 获取股票当前价格
        price = ''

        # 将信息封装到 Stock 对象并返回
        stock = StockDetail(stock_code, stock_name, price)
        print(f"获取到股票信息:{stock}")
        return stock
    else:
        print("无法获取数据，请检查股票代码或网络连接。")


def convert_stock_code(stock_code):
    # 去掉后缀并转换为小写
    return f"sz{stock_code[:-3].lower()}"
